﻿using System;
using System.Collections.Generic;
using System.Reflection;
using UnityEngine;
using UnityEditor;
using libxl;

namespace ExcelTool
{
    public class ExcelToDataStruct : EditorWindow
    {
        private static Dictionary<string, List<string>> PageData = new Dictionary<string, List<string>>();
        [MenuItem(@"Tool/ExcelToDataStruct #&s")]
        private static void ExcelToDataStructFunction()
        {
            string path = EditorUtility.OpenFilePanel("Please select the excel file.", "", "");
            if (path.Length == 0)
            {
                Debug.Log("No file.");
                return;
            }

            BinBook workBook = new BinBook();
            workBook.load(path);

            Sheet workSheet = workBook.getSheet(0);

            List<string> colData = new List<string>();
            string titleName = "";

            for (int j = workSheet.firstCol(); j < workSheet.lastCol(); ++j)
            {
                colData.Clear();
                titleName = workSheet.readStr(0, j);
                for (int i = workSheet.firstRow(); i < workSheet.lastRow(); ++i)
                {
                    colData.Add(workSheet.readStr(i, j));
                }
                PageData.Add(titleName, colData);
            }

            foreach (var item in PageData)
            {
                Console.WriteLine(item.Key + item.Value);
            }

        //    List<TestClassStruct> result = LoadData<TestClassStruct>("out.xls");
        }

        public static List<T> LoadData<T>(string fileName) where T : new()
        {
            if(string.IsNullOrEmpty(fileName.Trim()))
            {
                Debug.LogError("file name errot.");
                return null;
            }
            List<T> lst = new List<T>();

            BinBook workBook = new BinBook();
            workBook.load(Const.foldPath + fileName);

            Sheet workSheet = workBook.getSheet(0);

            for (int i = workSheet.firstRow(); i < workSheet.lastRow(); ++i)
            {
                for (int j = workSheet.firstCol(); j < workSheet.lastCol(); ++j)
                {
                    T data = ReadData<T>(workSheet.readStr(i, j));
                    lst.Add(data);
                }
            }

            return lst;
        }

        private static T ReadData<T>(string data) where T : new()
        {
            T t = new T();
            Type type = typeof(T); ;
            foreach (var item in type.GetProperties())
            {
               /* Debug.Log("类型：" + item.PropertyType.FullName + " 属性名：" + item.Name + " 值：" + item.SetValue(t, null));*/
            }
            PropertyInfo[] propertyInfos = type.GetProperties();
            foreach (var pi in propertyInfos)
            {

            }
            return t;
        }
    }

}
